package esjd.demo.utile;

import esjd.demo.pojo.Pordouct;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HttpUtile {

    public static void main(String[] args) throws IOException {
        getList("手机").forEach(System.out::println);

    }


    public static List<Pordouct> getList(String key){
        ArrayList<Pordouct> list = new ArrayList<>();
        System.getProperties().setProperty("webdriver.chrome.driver", "C:\\Users\\李庆\\Desktop\\学习中的\\ElasticSearch\\jd\\src\\main\\java\\chromedriver.exe");
        // 设置 chromedirver 的存放位置
        // 设置无头浏览器，这样就不会弹出浏览器窗口
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");

        WebDriver webDriver = new ChromeDriver(chromeOptions);
        webDriver.get("https://search.jd.com/Search?keyword="+key);
        WebElement webElements = webDriver.findElement(By.xpath("//div[@id='J_goodsList']"));  //获取div id为J_goodsList 下的html
        WebElement elements = webElements.findElement(By.xpath("//ul[@class='gl-warp clearfix']"));
        List<WebElement> elements4 = elements.findElements(By.xpath("//li[@class='gl-item']"));
        for (WebElement webElement : elements4) {
            WebElement li = webElement.findElement(By.className("gl-i-wrap"));
            String text = li.findElement(By.className("p-name")).getText();
             String price = li.findElement(By.className("p-price")).getText();
            // //*[@id="J_goodsList"]/ul/li[3]/div/div[1]/a/img
            String attribute=null;
            attribute = li.findElement(By.className("p-img")).findElement(By.tagName("a")).findElement(By.tagName("img")).getAttribute("src");
            if (attribute==null){              //tagName 当前xxx标签下的
                attribute="http:"+li.findElement(By.className("p-img")).findElement(By.tagName("a")).findElement(By.tagName("img")).getAttribute("data-lazy-img");

            }
            list.add(new Pordouct(text,price,attribute)); // Pordouct为我们封装商品信息的实体类
        }
         return list;
    }

}
